extends Node2D


const COIN_BUMPED = preload("res://sence/objects/coin_bumped.tscn")
const MUSH_ROOM = preload("res://sence/objects/mush_room.tscn")
const FLOWER = preload("res://sence/objects/flower.tscn")
const STAR = preload("res://sence/objects/star.tscn")
@onready var top_area_2d = $TopArea2D
@onready var bottom_area_2d = $BottomArea2D


var can_bump := true
const BUMP_HEIGHT := 8.0
const BUMP_DURATION := 0.1

func do_bump(reset := false) -> void:
	# 先往上顶一小段距离，然后下落回来
	var tween := create_tween()
	var originalY := owner.position.y as float
	tween.tween_property(owner, "position:y", originalY - BUMP_HEIGHT, BUMP_DURATION)
	await tween.finished
	tween = create_tween()
	tween.tween_property(owner, "position:y", originalY + 1, BUMP_DURATION)
	tween.tween_property(owner, "position:y", originalY, BUMP_DURATION)
	await tween.finished
	if reset:
		can_bump = true
		
		
func do_spawn(node: Node2D, item: Brick.SpawnItem, player: Node2D) -> void:
	var item_instance : Node2D
	
	match item:
		Brick.SpawnItem.COIN:
			item_instance = COIN_BUMPED.instantiate()
		Brick.SpawnItem.LIFE:
			item_instance = MUSH_ROOM.instantiate() as MushRoom
			item_instance.mushroom_type = Brick.SpawnItem.LIFE
		Brick.SpawnItem.UPGRADE:
			if player.curr_mode == Player.Mode.LARGE or player.curr_mode == Player.Mode.FIRE:
				item_instance = FLOWER.instantiate() as Flower
			else:
				item_instance = MUSH_ROOM.instantiate() as MushRoom
				item_instance.mushroom_type = Brick.SpawnItem.UPGRADE
		Brick.SpawnItem.STAR:
			item_instance = STAR.instantiate() as Star
	item_instance.global_position = node.global_position
	get_tree().root.call_deferred("add_child", item_instance)
	
# 把顶的效果应用到上方的物体
func apply_bump_effect() -> void:
	for area in bottom_area_2d.get_overlapping_areas():
		if area.owner.has_method("on_bumped"):
			area.owner.on_bumped(self)
	for body in bottom_area_2d.get_overlapping_bodies():
		print_debug(body.name)
		if body.has_method("on_bumped"):
			body.on_bumped(self)

func _on_bottom_area_2d_body_entered(body: Node2D) -> void:
	if body.name == "Player":
		owner.on_bumped(body)
